<script setup lang="ts">
import {
  parkAddEnApi,
  parkEditEnApi,
  parkGetBusinessLicenseApi,
  parkGetEnDetailApi,
  parkGetIndustryListApi,
} from '@/apis/park'
import type { EnAddParamsI, IndustryI } from '@/types/park'
import { ArrowLeft } from '@element-plus/icons-vue'
import {
  ElMessage,
  type UploadRequestOptions,
  type UploadUserFile,
} from 'element-plus'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
// 标题
let title = ref('')
// 参数
const defaultParams = {
  name: '',
  legalPerson: '',
  registeredAddress: '',
  industryCode: undefined,
  businessLicenseUrl: '',
  businessLicenseId: undefined,
  contact: '',
  contactNumber: '',
}
let params = ref<EnAddParamsI>({
  name: '',
  legalPerson: '',
  registeredAddress: '',
  industryCode: undefined,
  businessLicenseUrl: '',
  businessLicenseId: undefined,
  contact: '',
  contactNumber: '',
})
const rules = {
  name: [{ required: true, message: '企业名称为必填', trigger: 'blur' }],
  legalPerson: [{ required: true, message: '法人为必填', trigger: 'blur' }],
  registeredAddress: [
    { required: true, message: '注册地址为必填', trigger: 'blur' },
  ],
  industryCode: [
    { required: true, message: '所在行业为必填', trigger: 'change' },
  ],
  contact: [{ required: true, message: '企业联系人为必填', trigger: 'blur' }],
  contactNumber: [
    { required: true, message: '企业联系人电话为必填', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '请输入正确的手机号' },
  ],
  businessLicenseId: [
    { required: true, message: '请上传营业执照', trigger: 'change' },
  ],
}
// 接受路由参数并获取企业数据
const getEnData = async (id: any) => {
  if (id) {
    title.value = '编辑企业'
    const res = await parkGetEnDetailApi(id)
    const {
      businessLicenseId,
      businessLicenseUrl,
      contact,
      contactNumber,
      industryCode,
      legalPerson,
      name,
      registeredAddress,
      businessLicenseName,
    } = res
    params.value = {
      businessLicenseId,
      businessLicenseUrl,
      contact,
      contactNumber,
      industryCode,
      legalPerson,
      name,
      registeredAddress,
    }
    fileList.value.push({
      name: businessLicenseName,
      url: businessLicenseUrl,
    })
  } else {
    title.value = '添加企业'
  }
}
getEnData(route.query.id)
// 企业信息表单
const enFormRef = ref()
// 联系人信息表单
const contactFormRef = ref()
// 行业列表
let industryList = ref<IndustryI[]>([])
const getIndustryList = async () => {
  industryList.value = await parkGetIndustryListApi()
}
getIndustryList()
// 上传营业执照
// 文件列表
const fileList = ref<UploadUserFile[]>([])
// 上传文件
const uploadRequest = async (options: UploadRequestOptions) => {
  const { file } = options
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', 'businessLicense')
  const res = await parkGetBusinessLicenseApi(formData)
  params.value.businessLicenseId = res.id
  params.value.businessLicenseUrl = res.url
  // 单独校验表单，如果校验成功，自动清除错误信息
  enFormRef.value.validateField('businessLicenseId')
}
// 文件移除，清除文件信息
const removeFile = () => {
  params.value.businessLicenseId = undefined
  params.value.businessLicenseUrl = ''
}
// 确定
const onSubmit = async (id: any) => {
  await enFormRef.value.validate()
  await contactFormRef.value.validate()
  if (id) {
    await parkEditEnApi({ ...params.value, id: id })
    ElMessage.success('编辑成功~')
  } else {
    await parkAddEnApi(params.value)
    ElMessage.success('添加成功~')
  }
  onReset()
  router.back()
}
// 重置
const onReset = () => {
  params.value = { ...defaultParams }
  enFormRef.value.resetFields()
  contactFormRef.value.resetFields()
}
</script>

<template>
  <div class="add-enterprise">
    <header class="header-box">
      <el-page-header :icon="ArrowLeft" @back="$router.back()">
        <template #content>
          <span class="text-large font-600 mr-3">{{ title }}</span>
        </template>
        <template #extra>
          <span>黑马管理员</span>
        </template>
      </el-page-header>
    </header>
    <main class="main-box">
      <div class="form-container">
        <div class="title">企业信息</div>
        <el-form
          label-width="100px"
          :model="params"
          :rules="rules"
          ref="enFormRef"
        >
          <el-form-item label="企业名称:" prop="name">
            <el-input placeholder="请输入企业名称" v-model="params.name" />
          </el-form-item>
          <el-form-item label="法人:" prop="legalPerson">
            <el-input placeholder="请输入法人" v-model="params.legalPerson" />
          </el-form-item>
          <el-form-item label="注册地址:" prop="registeredAddress">
            <el-input
              placeholder="请输入注册地址"
              v-model="params.registeredAddress"
            />
          </el-form-item>
          <el-form-item label="所在行业:" prop="industryCode">
            <el-select
              v-model="params.industryCode"
              placeholder="请选择所在行业"
            >
              <el-option
                :label="item.industryName"
                :value="item.industryCode"
                v-for="item in industryList"
                :key="item.industryCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="营业执照:"
            prop="businessLicenseId"
            style="height: 81px"
          >
            <el-upload
              action="#"
              ref="upload"
              v-model:file-list="fileList"
              :http-request="uploadRequest"
              :on-remove="removeFile"
              :limit="1"
            >
              <el-button type="primary" size="small">上传文件</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  支持扩展名：.png .jpg .jpeg, 文件大小不得超过5M且
                  <span style="color: red">只能选择一张。</span>
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div class="form-container">
        <div class="title">联系人信息</div>
        <el-form
          label-width="100px"
          :model="params"
          :rules="rules"
          ref="contactFormRef"
        >
          <el-form-item label="企业联系人:" prop="contact">
            <el-input placeholder="请输入企业联系人" v-model="params.contact" />
          </el-form-item>
          <el-form-item label="联系电话:" prop="contactNumber">
            <el-input
              placeholder="请输入联系电话"
              v-model="params.contactNumber"
            />
          </el-form-item>
        </el-form>
      </div>
    </main>
    <footer class="footer-box">
      <el-button type="primary" class="btn-main" @click="onReset"
        >重置</el-button
      >
      <el-button
        type="primary"
        class="btn-main"
        @click="onSubmit($route.query.id)"
        >确定</el-button
      >
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .header-box {
    background-color: #fff;
    padding: 20px 20px;
  }

  .main-box {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
        border-bottom: 1px solid rgb(237, 237, 237, 0.9);
      }

      .el-form {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 20px;
        padding: 30px 65px 24px;

        .el-form-item {
          width: 50%;
        }
      }
    }
  }

  .footer-box {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
